﻿using System;
using System.Web.Mvc;
using System.Xml.Linq;
using Maple.Weixin.MP.Entities;
using Maple.Weixin.MP.Entities.JsonResult;
using Maple.Weixin.MP.Entities.Messages;

namespace Maple.Weixin.MP.MvcExtension
{
    public class WeixinResult : ContentResult
    {
        protected ResponseMessageBase responseMessage;

        private readonly WeixinResultType resultType;

        public WeixinResult(string content) {
            base.Content = content;
            this.resultType = WeixinResultType.Content;
        }

        public WeixinResult(ResponseMessageBase responseMessage) {
            if (responseMessage == null)
                throw new ArgumentNullException("responseMessage");
            this.responseMessage = responseMessage;
            this.resultType = WeixinResultType.ResponseMessage;
        }

        public WeixinResult(WeixinServiceResult result) {
            base.Content = result.errcode.ToString();
            this.resultType = WeixinResultType.ServiceResult;
        }

        public new string Content {
            get {
                switch (resultType) {
                    case WeixinResultType.ResponseMessage:
                        return responseMessage.MessageType == ResponseMessageType.Nothing
                            ? null
                            : responseMessage.ToXDocument().ToString(SaveOptions.None);
                }
                return base.Content;
            }
        }

        public override void ExecuteResult(ControllerContext context) {
            if (base.Content == null && this.Content != null) {
                context.HttpContext.Response.ClearContent();
                context.HttpContext.Response.ContentType = "text/xml";
                responseMessage.ToXDocument().Save(context.HttpContext.Response.OutputStream);
            }

            base.ExecuteResult(context);
        }
    }
}